package mo.leetcode_top;

import java.util.Stack;

public class L907 {

    public int sumSubarrayMins(int[] arr) {

        int len = arr.length;
        if (len == 0) {
            return 0;
        }
        if (len == 1) {
            return (int)arr[0];
        }


        int[] left = new int[len];
        int[] right = new int[len];

        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < len; i++) {
            while (!stack.isEmpty() && arr[stack.peek()] > arr[i]) {
                stack.pop();
            }
            if (!stack.isEmpty()) {
                left[i] = stack.peek();
            } else {
                left[i] = -1;
            }
            stack.push(i);
        }

        stack.clear();
        for (int i = len - 1; i >= 0; i--) {
            while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
                stack.pop();
            }
            if (!stack.isEmpty()) {
                right[i] = stack.peek();
            } else {
                right[i] = len;
            }
            stack.push(i);
        }

        long ans = 0;
        for (int i = 0; i < len; i++) {
            ans += (long) (i - left[i]) * (right[i] - i) % 1000000007 * arr[i] % 1000000007;
            ans %= 1000000007;
        }
        return (int)ans;
    }


    public static void main(String[] args) {
        L907 test = new L907();
    }

}
